package com.zp.self.module.工具.json转换.json_csv;

import org.apache.commons.io.FileUtils;
import org.json.*;

import java.io.*;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：by peng.zeng
 * @date ：Created 2021/9/3 15:05
 * @description ：整理
 */
public class Json2CsvOk_多文件多列2泵送量工作时长 {
    public static void main(String[] args) throws IOException {
        m4();
    }

    //分段组装String
    private static void m4() throws IOException {

        String outPathPart2 = "C:\\Users\\peng.zeng\\Desktop\\deviceData2.csv";
        File file = new File(outPathPart2);
        //step 1.主文件的读取
        JSONArray mainJson = getJson("C:\\Users\\peng.zeng\\Desktop\\导出设备信息.json");

        //step 2.其他列的读取
        JSONArray otherJson_0 = getJson("C:\\Users\\peng.zeng\\Desktop\\泵送量与小时.txt");
        addOtherAttribute(mainJson, otherJson_0, "deviceId","ErgonicType",
                "deliveredAmount", "Machine_Cockpit_Value9", "Software_version", "Software_version_and_release2");

        JSONArray otherJson_1 = getJson("C:\\Users\\peng.zeng\\Desktop\\工作时长108_2.json");
        addOtherAttribute(mainJson, otherJson_1, "deviceId", "hours");

        //step 3.数据字段的特殊处理
        handleField(mainJson);

        //step over.转换数据为csv文件
        //设备表头
        JSONObject jo = mainJson.getJSONObject(0);
        jo.put("Software_version","");

        String csv = CDL.rowToString(jo.names()) +CDL.toString(jo.names(),mainJson);
        FileUtils.writeStringToFile(file, csv, "utf-8", true);
    }



    /**
     * Description: 将其他json数据的熟悉融合到主json中
     * @param mainJson    主json
     * @param otherJson_0 其他列json
     */
    private static void addOtherAttribute(JSONArray mainJson, JSONArray otherJson_0, String joinString, String... fields) {
        //循环为mainJson 添加字段
        for (String field : fields) {
            //1.将otherJson_0 的fields转换为map
            Map<String, String> otherJson_Map = new HashMap<>();
            int length = otherJson_0.length();
            for (int i = 0; i < length; i++) {
                Map<String, Object> otherJsondata = otherJson_0.getJSONObject(i).toMap();
                String joinId = otherJsondata.getOrDefault(joinString, "").toString();
                if (joinId != null && otherJsondata.get(field) != null) {
                    String value = otherJsondata.getOrDefault(field, "").toString();
                    otherJson_Map.put(joinId, value);
                }
            }
            //2.将当前字段field，加入到mainJson
            int mainLength = mainJson.length();
            for (int i = 0; i < mainLength; i++) {
                JSONObject jsonObject = mainJson.getJSONObject(i);
                Map<String, Object> mainJsondata = jsonObject.toMap();
                String joinId = mainJsondata.getOrDefault(joinString, "").toString();
                if (joinId != null) {
                    jsonObject.put(field, otherJson_Map.get(joinId));
                }
            }
        }
    }

    /**
     * Description: 读取文件为json对象
     */
    private static JSONArray getJson(String inPath2) throws IOException {
        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(inPath2));
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "utf-8"), 5 * 1024 * 1024);// 用5M的缓冲读取文本文件
        JSONTokener jsonTokener = new JSONTokener(reader);
        JSONArray objects = new JSONArray(jsonTokener);
        fis.close();
        reader.close();
        return objects;
    }

    //-------------------  这里为特殊业务处理，代码不共用  -------------------


    /**
     * Description: 如果ergonicType=2，版本大于等于2.30的从工况取，小于2.30的opHours=optHours+etlHours
     */
    private static void handleField(JSONArray mainJson) {
        DecimalFormat df  = new DecimalFormat("######0.00");
        //2.将当前字段field，加入到mainJson
        int mainLength = mainJson.length();
        for (int i = 0; i < mainLength; i++) {
            JSONObject jsonObject = mainJson.getJSONObject(i);
            if( jsonObject.getInt("model_type") ==5085){
                getHours(df, jsonObject);
                if(!jsonObject.keySet().contains("Software_version"))
                    continue;
                jsonObject.put("Software_version_and_release2",jsonObject.getString("Software_version"));
                continue;
            }
            if(!jsonObject.keySet().contains("ErgonicType"))
                continue;
            //如果ergonicType=2，版本大于等于2.30的从工况取，小于2.30的opHours=optHours+etlHours
            String version = jsonObject.getString("Software_version_and_release2");
            if ((jsonObject.getInt("ErgonicType") == 2 && !checkVersion(version)) ) {
                getHours(df, jsonObject);
            }else{
                double machine_cockpit_value9 = jsonObject.getDouble("Machine_Cockpit_Value9");
                jsonObject.put("hours",machine_cockpit_value9);
            }
        }
    }

    private static void getHours(DecimalFormat df, JSONObject jsonObject) throws JSONException {
        double opt_hours = 0.0;
        double hours_108 = 0.0;
        if (jsonObject.get("opt_hours") != null && !jsonObject.get("opt_hours").toString().equals("null"))
            opt_hours = jsonObject.getDouble("opt_hours");
        if (jsonObject.get("hours") != null)
            hours_108 = jsonObject.getDouble("hours");
        jsonObject.put("hours", df.format(opt_hours + hours_108));
    }

    /**
     * version>=2.30 return true else return false;
     * @param version
     * @return
     */
    public static boolean checkVersion(String version){
        try{
            int n1 = 0;
            int n2 = 0;
            int len = 0;
            if(version==null){
                return false;
            }
            if(version.equals("")){
                return false;
            }
            if(version.startsWith("V")){
                version = version.substring(1);
            }
            if(version.indexOf(".")>0) {
                String[] arr = version.split("\\.");
                len = arr.length;
                if(len>0){
                    if("E2".equals(arr[0])){
                        arr[0]="2";
                    }
                    n1 = Integer.valueOf(arr[0]).intValue();
                    if(n1>2){
                        return true;
                    }else if(n1==2){
                        if(len>1){
                            n2 = Integer.valueOf(arr[1]).intValue();
                        }
                        if(n2>=30){
                            return true;
                        }
                    }
                }
            }else{
                n1 = Integer.valueOf(version).intValue();
                return n1>2;
            }
            return false;
        }catch (Exception e){
            return false;
        }
    }
}
